//
//  ShoppingCartDetailVC.m
//  ChineseCollegeStudentsNetwork
//
//  Created by Zheng on 2019/3/23.
//  Copyright © 2019 刘喆. All rights reserved.
//

#import "ShoppingCartDetailVC.h"
#import "OrderDetailProductCell.h"
#import "OrderListModel.h"
#import "WXApi.h"
#import "AddressListModel.h"

@interface ShoppingCartDetailVC () <UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) OrderListModel *model;
@property (nonatomic, strong) UITableViewCell *infoCell;

@property (nonatomic, strong) UILabel *priceLbl;
@property (nonatomic, strong) NSArray *addressArr;
@property (nonatomic, strong) AddressListModel *addressModel;

@property (nonatomic) CGFloat totalFee;
@property (nonatomic) NSInteger totalCount;


@end

@implementation ShoppingCartDetailVC

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kPayStatusNotification" object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payStatusAction:) name:@"kPayStatusNotification" object:nil];

    NSDictionary *param = @{@"siteId":@"32"};
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiPayGet" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        _addressArr = [AddressListModel mj_objectArrayWithKeyValuesArray:response[@"addressInfoList"]];
        [_tableView reloadData];
    } failure:^{
        
    }];


    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = UIColorFromRGBHex(0xfa7a09);
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setTitle:@"继续支付" forState:UIControlStateNormal];
    WEAK_SELF
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        STRONG_SELF
      
        [self payAction];
        
    }];
    [bottomView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(120);
    }];
    
    
    _totalFee = 0;
    _totalCount = 0;
    for (ShopingCartModel *model in _modelsArr) {
        _totalFee = _totalFee+model.fee.doubleValue*model.count.integerValue;
        _totalCount = _totalCount+model.count.integerValue;
    }
    
    _priceLbl = [[UILabel alloc] init];
    _priceLbl.textColor = UIColorFromRGBHex(0xfa7a09);
    _priceLbl.text = [NSString stringWithFormat:@"%.2f",_totalFee];
    [bottomView addSubview:_priceLbl];
    [_priceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btn.mas_left).offset(-10);
        make.centerY.mas_equalTo(0);
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.font = [UIFont systemFontOfSize:15];
    titleLbl.text = @"合计：";
    [bottomView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.priceLbl.mas_left);
        make.centerY.mas_equalTo(0);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionHeaderHeight = 0.001;
        _tableView.estimatedSectionFooterHeight = 0.001;
        [_tableView registerClass:[OrderDetailProductCell class] forCellReuseIdentifier:@"kCellID"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        [self.view addSubview:self.tableView];
        
        UIImageView *imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"banner_pic"]];
        imgv.frame = CGRectMake(0, 0, 0, 125);
        _tableView.tableHeaderView = imgv;
        
    }
    return _tableView;
}


#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 2) {
        return _modelsArr.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (!_infoCell) {
            _infoCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            _infoCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            NSArray *titlesArr = @[@"收货人：",@"联系电话：",@"收货地址："];
            for (int i = 0; i < titlesArr.count; i++) {
                UILabel *titleLbl = [[UILabel alloc] init];
                titleLbl.text = titlesArr[i];
                titleLbl.font = [UIFont systemFontOfSize:15];
                titleLbl.tag = 10000+i;
                titleLbl.frame = CGRectMake(15, 15+28*i, SCREEN_WIDTH-30, 18);
                [_infoCell.contentView addSubview:titleLbl];
            }
        }
        
        if (_addressArr.count > 0) {
            
            if (!_addressModel) {
                for (AddressListModel *obj in _addressArr) {
                    if( obj.isDefault.integerValue == 1) {
                        _addressModel = obj;
                    }
                }
            }
            
            
            
            UILabel *titleLbl1 = [_infoCell viewWithTag:10000];
            UILabel *titleLbl2 = [_infoCell viewWithTag:10001];
            UILabel *titleLbl3 = [_infoCell viewWithTag:10002];
            titleLbl1.text = @"";
            titleLbl2.text = @"";
            titleLbl3.text = @"";
            titleLbl1.text = [titleLbl1.text stringByAppendingString:_addressModel.realName];
            titleLbl2.text = [titleLbl2.text stringByAppendingString:_addressModel.mobile];
            titleLbl3.text = [titleLbl3.text stringByAppendingString:[NSString stringWithFormat:@"%@ %@",_addressModel.location,_addressModel.address]];
        }
        
        return _infoCell;
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"平邮";
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        return cell;
    } else if (indexPath.section == 2) {
        OrderDetailProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCellID" forIndexPath:indexPath];
        cell.model = _modelsArr[indexPath.row];
        return cell;
    } else if (indexPath.section == 3) {
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"微信支付";
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        return cell;
    }
    
    
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *titlesArr = @[@"收货信息",@"运送方式",@"商品清单",@"支付方式",@"其他"];
    return titlesArr[section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 104;
    } else if (indexPath.section == 1) {
        return 44;
    } else if (indexPath.section == 3) {
        return 44;
    }
    
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择收货地址" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        for (AddressListModel *model in _addressArr) {
            UIAlertAction *act = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@ %@",model.location,model.address] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                _addressModel = model;
                [_tableView reloadData];
            }];
            [alertVC addAction:act];
        }
        
        UIAlertAction *act =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:act];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertVC animated:YES completion:nil];
        });
        
    }
    
}

- (void)payAction {
    
    if (_modelsArr.count == 0) {
        return;
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    for (ShopingCartModel *model in _modelsArr) {
        [arr addObject:model.Id];
    }
    
    NSDictionary *param = @{@"addressId":_addressModel.id,
                            @"channel":@"app",
                            @"deliveryFee":[NSString stringWithFormat:@"%.2f",_totalFee],
                            @"isMobile":@"1",
                            @"message":@"",
                            @"siteId":@"32",
                            @"successUrl":@"",
                            @"totalCount":@(_totalCount),
                            @"totalFee":[NSString stringWithFormat:@"%.2f",_totalFee],
                            @"cartIdList":arr
                            };
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiPay" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        [self postWeiXinPay:response];
    } failure:^{
        
    }];

}

- (void)postWeiXinPay:(NSDictionary *)param {
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:param];
    [params setObject:@"producta" forKey:@"detail"];
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.magazine/WeiXinPay" params:params.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = [response objectForKey:@"partnerid"];
        req.prepayId            = [response objectForKey:@"prepayid"];
        req.nonceStr            = [response objectForKey:@"noncestr"];
        req.timeStamp           = [response[@"timestamp"] intValue];
        req.package             = [response objectForKey:@"packagestr"];
        req.sign                = [response objectForKey:@"sign"];
        [WXApi sendReq:req];
    } failure:^{
        
    }];
}

#pragma mark
- (void)payStatusAction:(NSNotification *)nofi {
    
    BaseResp *resp = (BaseResp *)nofi.object;
    
    switch (resp.errCode) {
        case WXSuccess:
        {
            ShowMessage(@"支付成功");
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
            break;
            
        default:
        {
            ShowMessage(@"支付失败");
        }
            break;
    }
}

@end
